package com.mondo.financialwallet.presentation.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.common.ui.AbsNetworkStateActivity;
import com.example.common.widget.state.NetworkStateLayout;
import com.example.common.zxing.encoding.EncodingHandler;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.MyTokenListEntity;
import com.mondo.financialwallet.data.entity.TokenAddressEntity;
import com.mondo.financialwallet.presentation.model.Token;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.ui.dialog.WalletTypeBottomSheetDialog;
import com.mondo.financialwallet.presentation.utils.AndroidUtils;
import com.mondo.financialwallet.presentation.utils.Toasts;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 收款
 */
public class TokenReceiptActivity extends AbsNetworkStateActivity implements WalletTypeBottomSheetDialog.OnClickListener {

    private static final String EXTRA_TOKEN_ID = "TOKEN_ID";

    public static void launch(Context context) {
        context.startActivity(new Intent(context, TokenReceiptActivity.class));
    }

    public static void launch(Context context, String tokenId) {
        context.startActivity(new Intent(context, TokenReceiptActivity.class)
        .putExtra(EXTRA_TOKEN_ID, tokenId));
    }

    @Bind(R.id.copy_code_view) View mCopyCodeView;
    @Bind(R.id.code_text_view) TextView mCodeTextView;
    @Bind(R.id.address_text_view) TextView mAddressTextView;
    @Bind(R.id.copy_address_view) View mCopyAddressView;
    @Bind(R.id.name_text_view) TextView mNameTextView;
    @Bind(R.id.rq_code_image_view) ImageView mRqCodeImageView;
    @Bind(R.id.select_token_layout) View mSelectTokenLayout;
    @Bind(R.id.rq_code_state_layout) NetworkStateLayout mRqCodeStateLayout;

    private String mTokenId;
    private WalletTypeBottomSheetDialog mSelectTokenDialog;

    @Override
    public int getTitleLayoutRes() {
        return R.layout.include_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_receipt;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_token_receipt);

        // 显示货币ID
        mTokenId = getIntent().getStringExtra(EXTRA_TOKEN_ID);

        // 复制地址
        mCopyAddressView.setOnClickListener(v -> {
            AndroidUtils.copyToChipBoard(v.getContext(), mAddressTextView.getText().toString());
            Toasts.success(R.string.message_copy_success);
        });

        // 显示
        mSelectTokenLayout.setOnClickListener(v -> {
            if (mSelectTokenDialog != null && !mSelectTokenDialog.isShowing()) {
                mSelectTokenDialog.show();
            }
        });

        // 我的钱包类型
        requestMyTokenList();
    }

    private void requestTokenAddress() {
        mRqCodeStateLayout.loadingNetwork();

        DataRepository.get().tokenAddress(mTokenId, result -> {
            if (result.isSuccess()) {
                mRqCodeStateLayout.successNetwork();
                TokenAddressEntity.DataBean data = result.getData();

                if (Integer.parseInt(mTokenId) >= 4){
                    mCodeTextView.setText(data.getUid());
                    // 复制
                    mCopyCodeView.setVisibility(View.VISIBLE);
                    mCopyCodeView.setOnClickListener(v ->
                            AndroidUtils.copyToChipBoard(this, data.getUid()));
                } else {
                    mCodeTextView.setText(null);
                    mCopyCodeView.setVisibility(View.GONE);
                }

                mAddressTextView.setText(data.getAddress());
                createRqCodeImage(data.getAddress());
            } else {
                mRqCodeStateLayout.errorNetwork(result.getMsg());
            }
        });
    }

    private void requestMyTokenList() {
        loadingNetwork();

        DataRepository.get().myTokenList(result -> {
            if (result.isSuccess()) {
                successNetwork();
                List<MyTokenListEntity.DataBean> data = result.getData();
                List<Token> tokens = transformToken(data);
                mSelectTokenDialog = new WalletTypeBottomSheetDialog(this, tokens);
                mSelectTokenDialog.setOnClickListener(this);

                // 显示货币信息
                displayTokenInfoInView(tokens);
            } else {
                errorNetwork(result.getMsg());
            }
        });
    }

    private void displayTokenInfoInView(List<Token> tokens) {
        Token token = null;
        if (TextUtils.isEmpty(mTokenId)) {
            token = tokens.get(0);
        } else {
            for (Token t : tokens) {
                if (t.getId().equals(mTokenId)) {
                    token = t;
                    break;
                }
            }
        }

        mTokenId = token.getId();
        mNameTextView.setText(token.getName());
        requestTokenAddress();
    }

    private List<Token> transformToken(List<MyTokenListEntity.DataBean> data) {
        List<Token> tokens = new ArrayList<>();
        for (MyTokenListEntity.DataBean datum : data) {
            Token t = new Token(
                    datum.getLogo(),
                    datum.getToken_id(),
                    datum.getTitle_en(),
                    String.valueOf(datum.getUsd()),
                    String.valueOf(datum.getBalance()));
            t.setAddress(datum.getAddress());
            tokens.add(t);
        }

        return tokens;
    }

    private void createRqCodeImage(String address){
        try {
            // 创建地址二维码图片
            Bitmap addressBitmap = EncodingHandler.createQRCode(address,
                    getResources().getDimensionPixelOffset(R.dimen.rq_code_image_size));
            mRqCodeImageView.setImageBitmap(addressBitmap);
            mRqCodeImageView.setBackgroundColor(Color.WHITE);

            // 保存地址图片
            //copyAddressImage.setOnClickListener(view -> ImageViews.saveImageToGallery(this, addressBitmap));
        } catch (Exception e) {
            Toasts.failure(e.getMessage());
            finish();
        }
    }

    @Override
    public void onClick(Token token) {
        mNameTextView.setText(token.getName());
        mTokenId = token.getId();
        requestTokenAddress();
    }

    @Override
    public void onAnewRequest() {
        requestMyTokenList();
    }
}
